﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace OverStore.Runtime.PersistenceServiceProvider
{
    /// <summary>
    /// Exposes set of static methods extends functionality of <see cref="IPersistenceServiceProvider"/> interface.
    /// </summary>
    public static class PersistenceServiceProviderExtensions
    {
        /// <summary>
        /// Gets the boxed identifier of specified entity if it is not null reference, otherwise returns null.
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <typeparam name="TIdentifier">The type of the identifier.</typeparam>
        public static object GetIdentifierOrNull<TEntity, TIdentifier>(this IRegistry registry, TEntity entity)
            where TEntity : class
        {
            if (Object.ReferenceEquals(registry, null))
                throw new ArgumentNullException("provider");
            return ReferenceEquals(entity, null) ? default(object) : registry.GetIdentifier<TEntity, TIdentifier>(entity);
        }

        /// <summary>
        /// Gets the instance of <typeparamref name="TInstance"/> with specified identifier. 
        /// If identifier argument is null reference or hasn't result, method returns null reference.
        /// </summary>
        /// <typeparam name="TInstance">The type of the instance.</typeparam>
        /// <typeparam name="TIdentifier">The type of the identifier.</typeparam>
        /// <param name="registry">The object used for obtain registry used for obtain instance by identifier.</param>
        /// <param name="id">The instance idendifier.</param>
        /// <returns>The instance of <typeparamref name="TInstance"/> type with specified identifier.</returns>
        public static TInstance GetInstance<TInstance, TIdentifier>(this IRegistry registry, Nullable<TIdentifier> id)
            where TInstance : class
            where TIdentifier : struct
        {
            if (registry == null)
                throw new ArgumentNullException("provider");
            if (id == null || !id.HasValue)
                return null;
            else
                return registry.GetInstance<TInstance, TIdentifier>(id.Value);
        }
    }
}
